// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// L [author] rhyme_lph
// E [email]  rhymelph@gmail.com
// s [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/transaction_entity.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/utils/transaction_type_utils.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_white_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_title_item.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/select/transaction_record_radio_item.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/bill/add_payment_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "addPaymentPage")
class AddPaymentPage extends StatefulWidget {
  @override
  _AddPaymentPageState createState() => _AddPaymentPageState();
}

class _AddPaymentPageState extends State<AddPaymentPage>
    with PagePresenter<AddPaymentPage, AddPaymentProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: S.current.make_payment,
      );

  @override
  Widget get buildEmptyWidget => ColoredBox(
        color: Colors.white,
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                Expanded(
                  child: super.buildEmptyWidget,
                ),
              ],
            ),
            _buildBottomBar()
          ],
        ),
      );

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                Expanded(
                  child: listBuilder<Tuple2<bool, List<TransactionEntity>>>(
                    selector: (_, __) => Tuple2(
                        __.hasUp,
                        __.transactionList == null
                            ? null
                            : List.from(__.transactionList)),
                    builder: (BuildContext context,
                            Tuple2<bool, List<TransactionEntity>> value,
                            Widget child) =>
                        SmartRefresher(
                      controller: provider.refreshController,
                      onRefresh: provider.onRefresh,
                      onLoading: provider.onLoadMore,
                      enablePullUp: value.item1,
                      child: value.item2 == null
                          ? super.buildLoadingWidget
                          : value.item2.length == 0
                              ? super.buildEmptyWidget
                              : CustomScrollView(
                                  slivers: buildSearchWidget(),
                                ),
                    ),
                  ),
                ),
              ],
            ),
            _buildBottomBar()
          ],
        ),
      );

  Widget _buildBottomBar() => Positioned(
      bottom: getDp(32) + MediaQuery.of(context).padding.bottom,
      left: 0.0,
      right: 0.0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          NormalFloatTextWhiteButton(
            title: S.current.cancel,
            onTap: provider.onCancel,
          ),
          SizedBox(
            width: getDp(15),
          ),
          NormalFloatTextButton(
            title: S.current.add,
            onTap: provider.onAdd,
          ),
        ],
      ));

  List<Widget> buildSearchWidget() {
    return provider.transactionMap.entries
        .toList()
        .map((e) => buildSliver(e.key, e.value))
        .toList();
  }

  Widget buildSliver(String title, List<TransactionEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sticky: false,
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data[i]),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return TransactionRecordTitleItem(
      title: _title,
    );
  }

  Widget buildSliverItem(TransactionEntity data) {
    TransactionEntity lastItemInList =
        provider.transactionMap.entries.toList().map((e) => e.value).last.last;

    return listBuilder<Tuple2<TransactionEntity, bool>>(
      selector: (_, __) => Tuple2(
          data,
          __.transactions.firstWhere((element) => element.id == data.id,
                  orElse: () => null) !=
              null),
      builder: (BuildContext context, Tuple2<TransactionEntity, bool> value,
              Widget child) =>
          Column(
        children: [
          TransactionRecordCheckBoxItem(
            onTap: () => provider.onSelect(value.item1),
            isSelect: value.item2,
            tag: TransactionTypeUtils.getTransactionType(
                value.item1.transactionType),
            name: value.item1.name ?? '',
            currencyCode: value.item1.currencyCode,
            time: DateTimeUtils.formatDateTimeString(value.item1.issuedAt),
            amount: value.item1.total?.toDouble(),
            billNumber: value.item1.number,
            isUnpaid:
                value.item1.status == 'open' && value.item1.employeeId == null,
            status: value.item1.isOverdue == 1 && value.item1.status == 'open'
                ? 'Overdue'
                : FormUtils.getStatus(
                    TransactionTypeUtils.getTransactionTypeStatus(
                        value.item1.transactionType),
                    value.item1.status,
                    value.item1.status == 'open' &&
                            value.item1.employeeId == null
                        ? 1
                        : 0),
          ),
          if (lastItemInList == value.item1) AppSpaces.h85(context)
        ],
      ),
    );
  }
}
